from base.base import BaseTask
import requests
import json
import datetime
import os
from base.notify import send


class MzyTask(BaseTask):
    currentPhone = ''

    def __init__(self, token):
        self.token = token
        return

    # 获取我的总积分
    def getMyTotalPoint(self):
        url = 'https://webapi.qmai.cn/web/catering/crm/total-points'
        headers = {
            "Host": "webapi.qmai.cn",
            "Content-Length": "30",
            "Promotion-Code": None,
            "Work-Wechat-Userid": None,
            "Store-Id": "211679",
            "Accept-Language": "zh-CN",
            "Work-Staff-Id": None,
            "Scene": "1256",
            "Qm-From-Type": "catering",
            "Multi-Store-Id": "[object Undefined]",
            "Qm-User-Token": self.token,
            "Work-Staff-Name": None,
            "User-Agent": "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/107.0.0.0 Safari/537.36 MicroMessenger/7.0.20.1781(0x6700143B) NetType/WIFI MiniProgramEnv/Windows WindowsWechat/WMPF WindowsWechat(0x6309091b) XWEB/8531",
            "Qz-Gtd": None,
            "Qm-From": "wechat",
            "Content-Type": "application/json",
            "Accept": "v=1.0",
            "Channelcode": None,
            "Xweb_xhr": "1",
            "Gdt-Vid": None
        }
        rep = requests.post(url, data={"appid": "wx6cff4ec7eaabc6db"}, headers=headers).json()
        if rep['code'] == 0:
            self.print_('当前总积分：' + str(rep['data']))
        else:
            self.print_(('获取总积分失败，原因=' + rep['message']))

    # 获取抢到详情
    def getSignDetail(self):
        '''
        "trace_id":"261f963c3967eaf86d61f2565913ec2c","data":{"totalDays":1,"signInCycle":2,"intraDay":1,"continuityTotal":1,"activityId":"745656309067620352","signInDateList":["2024-01-21"]},"status":true,"message":null,"code":0}
        '''
        headers = {
            "Host": "webapi.qmai.cn",
            "Content-Length": "30",
            "Promotion-Code": "",
            "Work-Wechat-Userid": "",
            "Store-Id": "211679",
            "Accept-Language": "zh-CN",
            "Work-Staff-Id": "",
            "Scene": "1256",
            "Qm-From-Type": "catering",
            "Multi-Store-Id": "[object Undefined]",
            "Qm-User-Token": self.token,
            "Work-Staff-Name": "",
            "User-Agent": "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/107.0.0.0 Safari/537.36 MicroMessenger/7.0.20.1781(0x6700143B) NetType/WIFI MiniProgramEnv/Windows WindowsWechat/WMPF WindowsWechat(0x6309091b) XWEB/8531",
            "Qz-Gtd": "",
            "Qm-From": "wechat",
            "Content-Type": "application/json",
            "Accept": "v=1.0",
            "Channelcode": "",
            "Xweb_xhr": "1",
            "Gdt-Vid": "",
            "Sec-Fetch-Site": "cross-site",
            "Sec-Fetch-Mode": "cors",
            "Sec-Fetch-Dest": "empty",
            "Referer": "https://servicewechat.com/wx6cff4ec7eaabc6db/140/page-frame.html",
            "Accept-Encoding": "gzip, deflate"
        }

        data = {
            "appid": "wx6cff4ec7eaabc6db"
        }
        rep = requests.post('https://webapi.qmai.cn/web/catering/integral/sign/detail', headers=headers,
                            data=json.dumps(data)).json()
        if rep['code'] == 0:
            # 获取签到总时间
            signTotalDays = rep['data']['totalDays']
            isSignToday = len(rep['data']['signInDateList']) > 0 and datetime.datetime.now().strftime("%Y-%m-%d") == \
                          rep['data']['signInDateList'][-1]
            if not isSignToday:
                # 执行签到
                if self.getSignIn(rep['data']['activityId']):
                    signTotalDays = signTotalDays + 1
            else:
                self.print_('今天已完成签到')
            self.print_('当月累计签到天数：' + str(signTotalDays))
        else:
            self.print_('获取详情信息失败，原因=', rep['message'])

    # 签到
    def getSignIn(self, activityId):
        url = 'https://webapi.qmai.cn/web/catering/integral/sign/signIn'
        headers = {
            "Host": "webapi.qmai.cn",
            "Content-Length": "118",
            "Promotion-Code": None,
            "Work-Wechat-Userid": None,
            "Store-Id": "211679",
            "Accept-Language": "zh-CN",
            "Work-Staff-Id": None,
            "Scene": "1256",
            "Qm-From-Type": "catering",
            "Multi-Store-Id": "[object Undefined]",
            "Qm-User-Token": self.token,
            "Work-Staff-Name": None,
            "User-Agent": "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/107.0.0.0 Safari/537.36 MicroMessenger/7.0.20.1781(0x6700143B) NetType/WIFI MiniProgramEnv/Windows WindowsWechat/WMPF WindowsWechat(0x6309091b) XWEB/8531",
            "Qz-Gtd": None,
            "Qm-From": "wechat",
            "Content-Type": "application/json",
            "Accept": "v=1.0",
            "Channelcode": None,
            "Xweb_xhr": '1',
            "Gdt-Vid": None,
            "Sec-Fetch-Site": "cross-site",
            "Sec-Fetch-Mode": "cors",
            "Sec-Fetch-Dest": "empty",
            "Referer": "https://servicewechat.com/wx6cff4ec7eaabc6db/140/page-frame.html",
            "Accept-Encoding": "gzip, deflate"
        }
        rep = requests.post(url,
                            data=json.dumps(
                                {"activityId": activityId, "mobilePhone": "15113996874", "userName": "微信用户",
                                 "appid": "wx6cff4ec7eaabc6db"}), headers=headers).json()
        if rep['code'] == 0:
            self.print_('签到成功！')
        else:
            self.print_('签到失败，原因=', rep['message'])
        return rep['code'] == 0

    # 获取我的信息
    def getMyInfo(self):
        headers = {
            "Host": "webapi.qmai.cn",
            "Promotion-Code": "",
            "Work-Wechat-Userid": "",
            "Store-Id": "211679",
            "Accept-Language": "zh-CN",
            "Work-Staff-Id": "",
            "Scene": "1256",
            "Qm-From-Type": "catering",
            "Multi-Store-Id": "[object Undefined]",
            "Qm-User-Token": self.token,
            "Work-Staff-Name": "",
            "User-Agent": "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/107.0.0.0 Safari/537.36 MicroMessenger/7.0.20.1781(0x6700143B) NetType/WIFI MiniProgramEnv/Windows WindowsWechat/WMPF WindowsWechat(0x6309091b) XWEB/8531",
            "Qz-Gtd": "",
            "Qm-From": "wechat",
            "Content-Type": "application/json",
            "Accept": "v=1.0",
            "Channelcode": "",
            "Xweb_xhr": "1",
            "Gdt-Vid": "",
            "Sec-Fetch-Site": "cross-site",
            "Sec-Fetch-Mode": "cors",
            "Sec-Fetch-Dest": "empty",
            "Referer": "https://servicewechat.com/wx6cff4ec7eaabc6db/140/page-frame.html",
            "Accept-Encoding": "gzip, deflate"
        }

        url = "https://webapi.qmai.cn/web/catering/crm/personal-info"

        rep = requests.get(url, params={"appid": "wx6cff4ec7eaabc6db"}, headers=headers).json()
        if rep['code'] == 0:
            self.currentPhone = rep['data']['mobilePhone']
            self.print_('当前登录账号：' + rep['data']['mobilePhone'])
        else:
            self.print_('获取token=[' + self.token + ']个人信息失败，原因=', rep['message'])
        return rep['code'] == 0

    def do_task(self):
        # 获取我的个人信息
        self.getMyInfo()
        # 获取签到信息，没签到并签到
        self.getSignDetail()
        # 获取当前积分信息
        self.getMyTotalPoint()
        self.print_('--账号：' + self.currentPhone + ' 任务执行完毕！--')
        self.print_('')
        return


MZY_TOKEN = '1@2@3'
if 'MZY_TOKEN' in os.environ:
    MZY_TOKEN = os.environ.get("MZY_TOKEN")
    print('获取到环境变量MZY_TOKEN=' + MZY_TOKEN)
if __name__ == '__main__':
    # 多个用@分隔
    token_list = MZY_TOKEN.split('@')
    print_list = []
    for i in range(len(token_list)):
        task = MzyTask(token_list[i])
        print_list.extend(task.run())
    send("蒙自源签到", print_list)
